package com.hxht.cmp.exception;

import com.hxht.cmp.common.enums.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author alice on 2018/1/23 0023.
 * @version 1.0
 * @since 1.0
 */
public class CustomExceptionHandler implements HandlerExceptionResolver {
    private final Logger log = LoggerFactory.getLogger(CustomExceptionHandler.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {
        log.error("request url:" + request.getRequestURI());
        log.error("system error now ,error message:" + e.getMessage());
        response.setCharacterEncoding("UTF-8");
        response.setStatus(HttpServletResponse.SC_OK);
        if (!(request.getHeader("accept").contains("application/json") || (request.getHeader("X-Requested-With") != null && request
                .getHeader("X-Requested-With").contains("XMLHttpRequest")))) {
            // 如果不是异步请求
            // Apply HTTP status code for error views, if specified.
            // Only apply it if we're processing a top-level request.
            ModelAndView mv = new ModelAndView();
            mv.addObject("global", e.getMessage());
            mv.setViewName("error");
            return mv;
        } else {// JSON格式返回
            log.error("error 信息将会以页面形式进行返回");
            try {
                PrintWriter writer = response.getWriter();
                writer.write(ResultCode.SERVER_ERROR.getMessage());
                writer.flush();
            } catch (IOException ex) {
                log.error(ex.getMessage());
            }
            return null;
        }
    }
}
